import React, { useEffect, useState } from 'react';
import { Space, Table, Tag, Button, message, Popconfirm, Modal, Checkbox, Form, Input } from 'antd';
import type { TableProps, PopconfirmProps, FormProps } from 'antd';
import request from '../../api/request'



function Index() {
  let [arr, setArr] = useState([])
  let [id, setid] = useState()
  let [title, settitle] = useState()
  const [form] = Form.useForm();
  const getData = () => {
    request.get('/user/getMasterSelfBlog', {
      params: {
        pageNum: 1,
        pageSize: 10
      }
    }).then(res => {
      console.log('列表', res)
      setArr(res.data.data)
    })
  }

  useEffect(() => {
    getData()
  }, [])

  interface DataType {
    key: string;
    name: string;
    age: number;
    address: string;
    tags: string[];
  }

  // 删除确认框
  const confirm: PopconfirmProps['onConfirm'] = (e) => {
    console.log(e);
    message.success('Click on Yes');
  };

  const cancel: PopconfirmProps['onCancel'] = (e) => {
    console.log(e);
    message.error('Click on No');
  };

  const del = (id) => {
    request.delete('/user/deleteBlog', {
      params: {
        blogId: id
      }
    }).then(res => {
      console.log('删除', res)
      getData()
      alert('删除成功')
    })
  }

  const columns: TableProps<DataType>['columns'] = [
    {
      title: '作者',
      dataIndex: 'author',
      key: 'age',
    },
    {
      title: '标签',
      dataIndex: 'title',
      key: 'name',
    },
    {
      title: '创建时间',
      dataIndex: 'update_time',
      key: 'address',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => bj(record)}>编辑</Button>
          <Popconfirm
            title="Delete the task"
            description="Are you sure to delete this task?"
            onConfirm={() => del(record.id)}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 对话框
  const [isModalOpen, setIsModalOpen] = useState(false);

  const showModal = () => {
    setIsModalOpen(true);
    settitle('新增数据')
    form.resetFields();
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  type FieldType = {
    username?: string;
    password?: string;
    remember?: string;
  };

  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    console.log('Success:', values);

    if (title == '新增数据') {
      request.post('/user/addBlog', {
        title: values.title
      }).then(res => {
        console.log('新增', res)
        if (res.data.status == 200) {
          getData()
          setIsModalOpen(false);
          alert('新增成功')
        }
      })
    }
    else {
      request.put('/user/updateBlog', {
        blogId: id,
        title: values.title,
        editContent: values.title,
        showContent: values.title,
        tag: [],
        author: values.title,

      }).then(res => {
        console.log('编辑', res)
        if(res.data.status==200){
          getData()
          alert('编辑成功')
          setIsModalOpen(false);

        }
      })
    }

  };

  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };


  const bj = (record) => {
    form.setFieldsValue(record);
    setid(record.id)
     setIsModalOpen(true);
    settitle('编辑数据')
  }

  return (
    <div>
      <>
        <Button type="primary" onClick={showModal}>
          新增数据
        </Button>
        <Modal
          title={title}
          closable={{ 'aria-label': 'Custom Close Button' }}
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <Form
          form={form}
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item<FieldType>
              label="作者"
              name="title"
              rules={[{ required: true, message: 'Please input your username!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item label={null}>
              <Button type="primary" htmlType="submit">
                确定
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </>
      <Table<DataType> columns={columns} dataSource={arr} />
    </div>
  )
}

export default Index
